# Virtual Machine Compiler Makefile

CC = gcc
CFLAGS = -Wall -O0 -g3 -ggdb -fPIC
LDFLAGS = -shared

# Platform-specific settings
ifeq ($(OS),Windows_NT)
    LIB_SUFFIX = .dll
    LOCAL_TARGET = cvm2.dll
else
    UNAME_S := $(shell uname -s)
    ifeq ($(UNAME_S),Darwin)
        LIB_SUFFIX = .dylib
        LOCAL_TARGET = libcvm2.dylib
    else
        LIB_SUFFIX = .so
        LOCAL_TARGET = libcvm2.so
    endif
endif

# Library path definition - use the value passed from the top-level Makefile if provided
LIB_DIR ?= ../lib

# Target file name
TARGET = cvm2$(LIB_SUFFIX)

# Source files and object files
SRC = c_vm.c
OBJ = $(SRC:.c=.o)

# Header file directory
INCLUDES = -I../

# Default target
all: build_dependencies $(LIB_DIR)/$(TARGET) $(LOCAL_TARGET)

# Make sure dependencies are built first in the correct order
build_dependencies:
	$(MAKE) -C ../core all

# Build dynamic library, link to core library
$(LIB_DIR)/$(TARGET): $(OBJ)
	@mkdir -p $(LIB_DIR)
	$(CC) $(LDFLAGS) -o $@ $(OBJ) -L$(LIB_DIR) -lcore2
	@echo "Built vm library: $@"

# Build local copy of the shared library
$(LOCAL_TARGET): $(OBJ)
	$(CC) $(LDFLAGS) -o $@ $(OBJ) -L$(LIB_DIR) -lcore2
	@echo "Built vm library locally: $@"

# Compilation rule
%.o: %.c
	$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

# Clean rule
clean:
	rm -f $(OBJ)
	rm -f $(LIB_DIR)/$(TARGET) $(LOCAL_TARGET)
	@echo "VM module cleaned"

.PHONY: all clean build_dependencies 